package com.wenhuitec.android.tang.sysui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wenhuitec.android.tang.R;

import java.math.BigDecimal;

public class AddAndDecreaseButton extends LinearLayout {
    private int amount = 1;     //数量

    private String maxNumber = "999";
    private TextView etAmount;
    private Button btnDecrease;
    private Button btnIncrease;
    private AddAndDecreOnClick addAndDecreOnClick;

    public void setAddAndDecreOnClick(AddAndDecreOnClick addAndDecreOnClick) {
        this.addAndDecreOnClick = addAndDecreOnClick;
    }

    public AddAndDecreaseButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.view_add_and_decrease_button, this);
        etAmount = findViewById(R.id.etAmount);
        btnDecrease = findViewById(R.id.btnDecrease);
        btnIncrease = findViewById(R.id.btnIncrease);

        //设置‘-’号按键点击事件
        btnDecrease.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (amount > 1)
                    amount--;
                else
                    Toast.makeText(getContext(), "已是最小数量", Toast.LENGTH_SHORT).show();

                etAmount.setText(String.valueOf(amount));
                if (addAndDecreOnClick != null) {
                    addAndDecreOnClick.onUserClick(0, amount);
                }

            }
        });

        //设置‘+’号按键点击事件
        btnIncrease.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (new BigDecimal(amount + 1).compareTo(new BigDecimal(maxNumber)) <= 0) {
                    amount++;
                    etAmount.setText(String.valueOf(amount));
                    if (addAndDecreOnClick != null) {
                        addAndDecreOnClick.onUserClick(1, amount);
                    }
                }
            }
        });
    }

    public void setText(int amount) {
        this.amount = amount;
        etAmount.setText(String.valueOf(amount));
    }

    public void setText(int amount, String maxNumber) {
        this.amount = amount;
        this.maxNumber = maxNumber;
        etAmount.setText(String.valueOf(amount));
    }

    public interface AddAndDecreOnClick {
        public void onUserClick(int type, int amount);
    }

}
